package com.probiz.estoremf.customer.web.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import com.probiz.estore.common.model.content.SystemMessage;
import com.probiz.estore.content.service.SystemMessageManager;
import com.probiz.estore.core.controller.ControllerConstants;
import com.probiz.estore.core.controller.GenericCustomerFrontController;
import com.probiz.estore.core.search.SearchCriteria;
import com.probiz.estore.webapp.util.RequestContext;
import com.probiz.estore.webapp.util.RequestUtil;

public class SystemMessageFrontController extends GenericCustomerFrontController<SystemMessage> {
    private SystemMessageManager systemMessageManager=null;
    
    public void setSystemMessageManager(
            SystemMessageManager systemMessageManager) {
        this.systemMessageManager = systemMessageManager;
    }

	@Override
	protected String getEntityName(SystemMessage entity) {
		return null;
	}

	@Override
	protected Map<Integer, Map<String, Object>> getMultiSaveModel(
			HttpServletRequest request) {
		return null;
	}

	@Override
	protected void initController() throws Exception {
		mgr = systemMessageManager;
	}

	@Override
	protected void preSave(HttpServletRequest request, SystemMessage entity,
			BindException errors) {
		
	}
    
    @Override
    public ModelAndView defaultAction(HttpServletRequest request,
    		HttpServletResponse response) {     
		ModelAndView mv = new ModelAndView("customer/csSystemMessagesNeverRead");
		setLastSearchViewAllowed(false);
    	SearchCriteria sc = createSearchCriteria(request,SystemMessage.FilterHqlName.MY_SYSTEM_MESSAGE_STATUS_LIST);
    	sc.removeParamValues();
		sc.addParamValue(RequestContext.getCurrentUserId());
		sc.addParamValue(SystemMessage.MESSAGE_NEVER_READ);
		List<SystemMessage> systemMessageList = this.searchByCriteria(sc);
		mv.addObject("systemMessagesList", systemMessageList);
		return mv;
    }
    @Override
    public ModelAndView edit(HttpServletRequest request,
    		HttpServletResponse response) {
    	Integer messageId = RequestUtil.getInteger(request, "messageId");
    	SystemMessage systemMessage = systemMessageManager.loadById(messageId);
    	ModelAndView mv = new ModelAndView("customer/csSystemMessageDetail");
    	mv.addObject("systemMessage", systemMessage);
    	return mv;
	}
    
    public ModelAndView readMessage(HttpServletRequest request,
    		HttpServletResponse response) {
    	Integer messageId = RequestUtil.getInteger(request, "messageId");
    	SystemMessage systemMessage = systemMessageManager.loadById(messageId);
    	Map<String, Object> data = new HashMap<String, Object>();
    	data.put("messageId", messageId);
    	try{
	    	systemMessageManager.readMessage(messageId);
	    	data.put("result", 1);
    	}catch (Exception e) {
    		data.put("result", 0);
		}
    	data.put("content", systemMessage.getMessageHtml());
    	return getModelAndAjaxJsonView(data);
	}
    
    public ModelAndView delMessage(HttpServletRequest request,
    		HttpServletResponse response) {
    	Integer messageId = RequestUtil.getInteger(request, "messageId", -1);
    	String type = RequestUtil.getParameterDefaultSafe(request, "type", "A");
    	try{
    		SystemMessage systemMessage = systemMessageManager.loadById(messageId);
    		//String entityName = getEntityName(systemMessage);
    		String message = getMessage("common.message.deleted", new Object[] {getEntityTypeMessage(), systemMessage.getSystemMessageName() });
    		systemMessageManager.deleteById(systemMessage.getSystemMessageId());
    		saveMessage(request, message);
    	}catch (Exception e) {
			e.printStackTrace();
			this.saveErrorMessage(request, this.getMessage("common.message.delete.constraintViolation"));
		}
    	Integer prmPageNo = RequestUtil.getInteger(request, ControllerConstants.PRM_PAGENO);
    	prmPageNo = prmPageNo==null?1:prmPageNo;
    	request.getSession().setAttribute("tmpPrmPageNo", prmPageNo);
    	if("A".equals(type)){
    		return getRedirectView("/customer/csSystemMessages.html?doAction=readAllMessage");//getRedirectToActionView("toReadAllMessage");
    		//return readAllMessage(request,response);
    	}else{
    		return getRedirectView("/customer/csSystemMessages.html?doAction=defaultAction");
    		//return getRedirectToActionView("toDefaultAction");
    		//return defaultAction(request, response);
    	}
    }
    
    public ModelAndView readAllMessage(HttpServletRequest request,
    		HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("customer/csSystemMessages");
		setLastSearchViewAllowed(false);
    	SearchCriteria sc = createSearchCriteria(request,SystemMessage.FilterHqlName.MY_SYSTEM_MESSAGE_LIST);
    	int prmPageNo = getPageNo(request);
    	mv.addObject(ControllerConstants.PRM_PAGENO, prmPageNo); 
    	sc.changePaging(prmPageNo, sc.getPageSize());
		sc.removeParamValues();
		sc.addParamValue(RequestContext.getCurrentUserId());
		List<SystemMessage> systemMessageList = this.searchByCriteria(sc);
		mv.addObject("systemMessagesList", systemMessageList);
		return mv;
    }

    /**
     * 先从session中读取页码，如果没有，再从request中读取;
     * 主要是因为删除后，产生一些跳页问题;
     * @return
     */
	private int getPageNo(HttpServletRequest request) {
		Object pageNoObj = request.getSession().getAttribute("tmpPrmPageNo");
		int pageNo = 1;
		if(pageNoObj!=null){
			pageNo = Integer.parseInt(pageNoObj.toString());
			request.getSession().removeAttribute("tmpPrmPageNo");
		}else{
			pageNo = RequestUtil.getInteger(request, "PrmPageNo", 1);
		}
		return pageNo;
	}
    
	/**
	 * 批量删除系统消息
	 */
	 public ModelAndView delAllMessage(HttpServletRequest request,
	    		HttpServletResponse response) {
	    	String type = RequestUtil.getParameterDefaultSafe(request, "type", "A");
	    	String ids = request.getParameter("messageIds");
	    	try{
	    		String[] messageIds = ids.split(","); 
	    		String message = getMessage("systemMessage.delete.success");
	    		systemMessageManager.deleteAllByIds(messageIds);
	    		saveMessage(request, message);
	    	}catch (Exception e) {
				e.printStackTrace();
				this.saveErrorMessage(request, this.getMessage("common.message.delete.constraintViolation"));
			}
	    	Integer prmPageNo = RequestUtil.getInteger(request, ControllerConstants.PRM_PAGENO);
	    	prmPageNo = prmPageNo==null?1:prmPageNo;
	    	request.getSession().setAttribute("tmpPrmPageNo", prmPageNo);
	    	if("A".equals(type)){
	    		return getRedirectView("/customer/csSystemMessages.html?doAction=readAllMessage");//getRedirectToActionView("toReadAllMessage");
	    		//return readAllMessage(request,response);
	    	}else{
	    		return getRedirectView("/customer/csSystemMessages.html?doAction=defaultAction");
	    		//return getRedirectToActionView("toDefaultAction");
	    		//return defaultAction(request, response);
	    	}
	    }
    
}
